package com.ruoyi.framework.web.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.WxV3PayConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.*;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.domain.vo.WxLoginVo;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }


    // 微信登录
    @Transactional
    public AjaxResult loginOpenid(WxLoginVo wxLoginVo) {
        try {
            AjaxResult ajax = AjaxResult.success();
            // 微信小程序ID
            String appid = WxV3PayConfig.APP_ID;
            // 微信小程序秘钥
            String secret = WxV3PayConfig.secret;

            // 根据小程序穿过来的code想这个url发送请求
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + wxLoginVo.getCode() + "&grant_type=authorization_code";
            // 发送请求，返回Json字符串
            String str = WeChatUtil.httpRequest(url, "GET", null);
            // 转成Json对象 获取openid
            JSONObject jsonObject = JSONObject.parseObject(str);
            // 我们需要的openid，在一个小程序中，openid是唯一的
            String openid = jsonObject.get("openid").toString();
            String sessionKey = jsonObject.get("session_key").toString();
            wxLoginVo.setSessionKey(sessionKey);
            SysUser sysUser = new SysUser();
            if (StringUtils.isNotEmpty(openid)){
                String phoneNumber = this.getPhoneNumber(wxLoginVo);
                //先用电话号码判断有无此用户
//                BaUser baUser=new BaUser();
//                baUser.setPhoneNumber(phoneNumber);
//                List<BaUser> bausers= baUserService.selectBaUserList(baUser);
//                if(bausers.size()!=0){
//                    baUser=bausers.get(0);
//                }
                SysUser sysUserParam=new  SysUser();
                sysUserParam.setPhonenumber(phoneNumber);
               List<SysUser> sysUsers=  userService.selectAllocatedList(sysUserParam);
                //用户不存在
                String password="123456";
                if (sysUsers.size()==0){
                    //保存用户信息
                    String randomNickname = generateRandomNickname(5);
                    sysUser.setNickName("用户" + randomNickname);
                    //sysUser.setRoleId(Long.parseLong(RoleNameEnums.DOMESTIC_CONSUMER.getType().toString()));
                    sysUser.setUserName(phoneNumber);
                    sysUser.setPhonenumber(phoneNumber);
                    sysUser.setOpenId(openid);
                    sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
                    userService.insertUser(sysUser);
//                    //同时插入业务用户
//                    StockUser stockUser=new StockUser();
//                    stockUser.setSysUserid(sysUser.getUserId());
//                    stockUserService.insertStockUser(stockUser);
                }else {
                    sysUser=sysUsers.get(0);
                    sysUser.setOpenId(openid);
                    userService.updateUser(sysUser);
                }
                //用户存在
                String token = this.login2(sysUser.getUserName(),password);
                ajax.put(Constants.TOKEN, token);
            }
            return ajax;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("登录失败，请联系管理员！");
        }
    }

    public String getPhoneNumber( WxLoginVo getPhoneVo) throws Exception {

        //获取accessToken
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"
                + "?access_token=" + accessToken;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", getPhoneVo.getPhoneCode());
        String reqJsonStr = JSONObject.toJSONString(jsonObject);
        JSONObject wxJson = JSON.parseObject(HttpClientSslUtils.doPost(url, reqJsonStr));
        String phone_info = wxJson.getString("phone_info");
        JSONObject phone_info1 = JSONObject.parseObject(phone_info);
        String phoneNumber = null;
        try {
            phoneNumber = phone_info1.getString("phoneNumber");
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException("获取用户手机号失败！");
        }
        return phoneNumber;

    }

    private  String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token" +
                "?grant_type=client_credential" +
                "&appid=" + WxV3PayConfig.APP_ID +
                "&secret=" + WxV3PayConfig.secret;

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        String responseBody = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(responseBody);

        return jsonObject.getString("access_token");
    }


    public String login2(String username, String password) {
        // 验证码校验
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);

    }



    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    private String generateRandomNickname(int length) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            if (random.nextBoolean()) {
                // 添加数字
                sb.append(random.nextInt(10));
            } else {
                // 添加字母
                char c = (char) (random.nextInt(26) + 'a');
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
